package com.bucket.cloud.log.listener;

import com.bucket.cloud.common.core.constants.QueueConstants;
import com.bucket.cloud.common.core.model.SystemLog;
import com.bucket.cloud.common.core.util.BeanConvertUtils;
import com.bucket.cloud.log.api.model.GatewayAccessLogs;
import com.bucket.cloud.log.dao.GatewayLogsMapper;
import com.bucket.cloud.log.service.IpRegionService;
import com.bucket.cloud.log.service.LogService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description : 日志MQ消息监听器
 * ---------------------------------
 * @Author : cyq
 * @Date : Create in 2018/11/20 14:02
 */
@Component
public class LogMqListener {

    @Autowired
    private LogService logService;
    @Resource
    GatewayLogsMapper gatewayLogsMapper;
    /**
     * 临时存放减少io
     */
    @Autowired
    private IpRegionService ipRegionService;


//    @KafkaListener(topics = "${mq.log.queue}")
//    public void process(ConsumerRecord<?,String> record) {
//        JSONObject jobj = (JSONObject) JSONObject.parse(record.value());
//
//        logService.addNewLog(jobj.toJavaObject(SystemLog.class));
//    }

    /**
     * @Author: cyq
     * @Description: 系统操作日志保存
     * @Date: 2019/10/23 8:29 PM
     * @Params:
     * @Return:
     */
    @RabbitListener(queues = QueueConstants.QUEUE_SYSTEM_CUSTOM_LOGS)
    public void process(@Payload SystemLog log) {
        logService.addNewLog(log);
    }

    /**
     * @Author: cyq
     * @Description: 网关日志监听保存
     * @Date: 2019/10/23 8:29 PM
     * @Params:
     * @Return:
     */
    @RabbitListener(queues = QueueConstants.QUEUE_ACCESS_LOGS)
    public void apiLog(@Payload Map<String, Object> access) {
        GatewayAccessLogs logs = BeanConvertUtils.mapToObject(access, GatewayAccessLogs.class);
        if (logs != null) {
            if (logs.getIp() != null) {
                logs.setRegion(ipRegionService.getRegion(logs.getIp()));
            }
            logs.setUseTime(logs.getResponseTime().getTime() - logs.getRequestTime().getTime());
            gatewayLogsMapper.insert(logs);
        }


    }


}
